package com.ease.document.flyingsaucer;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.LinkedHashMap;
import java.util.Map;

import org.xhtmlrenderer.pdf.ITextFSImage;
import org.xhtmlrenderer.pdf.ITextOutputDevice;
import org.xhtmlrenderer.pdf.ITextUserAgent;
import org.xhtmlrenderer.resource.CSSResource;
import org.xhtmlrenderer.resource.ImageResource;
import org.xhtmlrenderer.util.XRLog;

import com.lowagie.text.Image;

/**
 * 修改xhtmlrenderer获取css和image资源的方法为网络
 * 
 * <a href="http://www.javaeye.com/topic/509417?page=5" />
 * 
 * @author yye_javaeye
 */
public class HttpUrlUserAgent extends ITextUserAgent {

	/** LRU cache */
	private int imageCacheCapacity = 16;

	private Map<String, ImageResource> imageCache = new LinkedHashMap<String, ImageResource>(imageCacheCapacity, 0.75f, true) {

		/**
		 * 
		 */
		private static final long serialVersionUID = -4770174944434534332L;

		protected boolean removeEldestEntry(java.util.Map.Entry<String, ImageResource> eldest) {
			return size() > imageCacheCapacity;
		}
	};

	public HttpUrlUserAgent(ITextOutputDevice outputDevice) {
		super(outputDevice);
	}

	public CSSResource getCSSResource(String uri) {
		InputStream is = null;
		uri = resolveURI(uri);
		try {
			URLConnection uc = new URL(uri).openConnection();
			uc.connect();
			is = uc.getInputStream();
		} catch (MalformedURLException e) {
			XRLog.exception("bad URL given: " + uri, e);
		} catch (IOException e) {
			XRLog.exception("IO problem for " + uri, e);
		}
		return new CSSResource(is);
	}

	public ImageResource getImageResource(String uri) {
		ImageResource ir;
		uri = resolveURI(uri);
		ir = (ImageResource) imageCache.get(uri);
		if (ir == null) {
			try {
				ir = new ImageResource(new ITextFSImage(Image.getInstance(new URL(uri))));
			} catch (Exception e) {
				e.printStackTrace();
			}
			imageCache.put(uri, ir);
		}
		if (ir == null)
			ir = new ImageResource(null);
		return ir;
	}
}